package com.ccl.iot.huiju;

import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ccl.iot.App;
import com.ccl.iot.R;
import com.ccl.iot.dvr.utils.LogUtil;
import com.ccl.iot.dvr.utils.ToastUtil;
import com.ccl.iot.huiju.adapter.MainAdapter;
import com.ccl.iot.huiju.contract.MainContract;
import com.ccl.iot.huiju.presenter.MainPresenterImpl;
import com.ccl.iot.publics.UIUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;


/**
 * 类说明：主界面
 * 作者：HD on 2017/10/24 17:33
 * 邮箱：hehandong@qq.com
 */
public class MainFragment extends BaseFragment implements MainContract.MainView {

    //-----------------UI--------------------
    private GridView mGridView;
    private MainAdapter mMainAdapter;
    private RelativeLayout mLeftLayout;
    private RelativeLayout mRightLayout;

    public MainFragmentListener mMainFragmentListener;
    private RelativeLayout mLogoLayout;

    private ImageView mLeftImg;
    private ImageView mRightImg;

    private ImageView mErrorImg;
    private TextView mErrorTv;
    private Animation mCircleAnim;
    private RelativeLayout mErrorLayout;


    //-----------------Data--------------------

    public final static String TAG = "MainFragment";

    private static final int ERROR_NO_WIFI = 0x01;
    private static final int ERROR_NO_DATA = 0x02;
    private static final int ERROR_LOADING = 0x03;

    public final static int SHOW_ERRORLAYOUT_EVENT = 10;

    private SparseArray<IOTHuiJu> mDataList;

    private int mPositionPageIndex;
    private ArrayList<IOTHuiJu> mIOTHuiJuList;

    private int mLeftClickCount;
    private int mRightClickCount;

    private float mPoint2DownX;

    private float mPoint2MoveX;
    private MainPresenterImpl mMainPresenter;

    private int mDataSize;


    @Override
    public void setLeftLayoutVisibility(int visibility) {
        if (mLeftLayout != null) {
            mLeftLayout.setVisibility(visibility);
        }
    }

    @Override
    public void setRightLayoutVisibility(int visibility) {
        if (mRightLayout != null) {
            mRightLayout.setVisibility(visibility);
        }
    }

    @Override
    public void notifyDataSetChanged(SparseArray<IOTHuiJu> datas, int pageIndex, int size) {

        if (mMainAdapter != null) {
            mDataList = datas;
            mDataSize = size;
            mMainAdapter.notifyDataSetChanged(datas);
            if (pageIndex == 0) {
                if (mHandler.hasMessages(SHOW_ERRORLAYOUT_EVENT)) {
                    mHandler.removeMessages(SHOW_ERRORLAYOUT_EVENT);
                }
                if (size == 0) {
//                    LogUtil.e(TAG, "------mHandler.sendEmptyMessageDelayed(NOTIFY_MAINFRAGMENT, 6000)");
                    mHandler.sendEmptyMessageDelayed(SHOW_ERRORLAYOUT_EVENT, 6000);
                } else {
//                    LogUtil.e(TAG, "------mHandler.sendEmptyMessage(NOTIFY_MAINFRAGMENT)");
                    mHandler.sendEmptyMessage(SHOW_ERRORLAYOUT_EVENT);
                }
            }
        }
        mPositionPageIndex = pageIndex;
    }

    public interface MainFragmentListener {
        void goToEditFrag();

        void reScanDevice();
    }

    public void setMainFragmentListener(MainFragmentListener listener) {
        mMainFragmentListener = listener;
    }


    public MainFragment() {
        // Required empty public constructor
    }


    private static class MainFragmentHandler extends Handler {
        private final WeakReference<MainFragment> mFragment;

        public MainFragmentHandler(MainFragment fragment) {
            mFragment = new WeakReference<MainFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            MainFragment mainFragment = mFragment.get();

            if (mainFragment != null) {

                switch (msg.what) {

                    case SHOW_ERRORLAYOUT_EVENT:
                        mainFragment.showErrorLayoutEvent();
                        break;

                    default:

                        break;
                }
            }
        }
    }

    private final MainFragmentHandler mHandler = new MainFragmentHandler(this);

    public static MainFragment newInstance() {
        MainFragment fragment = new MainFragment();
        return fragment;
    }

    @Override
    protected View setContentView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_main_item, container, false);
    }

    @Override
    protected void initView(View view) {


        mDataList = new SparseArray<>();

        mGridView = (GridView) view.findViewById(R.id.gridView_main);

        mMainAdapter = new MainAdapter(mContext, mDataList);

        mGridView.setAdapter(mMainAdapter);

        mLeftLayout = (RelativeLayout) view.findViewById(R.id.layout_left);

        mRightLayout = (RelativeLayout) view.findViewById(R.id.layout_right);

        mLogoLayout = (RelativeLayout) view.findViewById(R.id.layout_logo);

        mLeftImg = (ImageView) view.findViewById(R.id.iv_main_left);

        mRightImg = (ImageView) view.findViewById(R.id.iv_main_right);

        mErrorLayout = (RelativeLayout) view.findViewById(R.id.layout_error);
        mErrorImg = (ImageView) view.findViewById(R.id.iv_error);
        mErrorTv = (TextView) view.findViewById(R.id.tv_error);

        mCircleAnim = AnimationUtils.loadAnimation(getContext(), R.anim.anim_round_rotate);
        LinearInterpolator interpolator = new LinearInterpolator();
        mCircleAnim.setInterpolator(interpolator);


    }


    @Override
    protected void initListener() {

        if (getActivity() instanceof MainFragmentListener) {
            LogUtil.i(TAG, "setMainFragmentListener");
            setMainFragmentListener((MainFragmentListener) getActivity());
        }


        mLeftImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLeftClickCount++;
                if (mLeftClickCount == 5) {
                    mLeftClickCount = 0;

                    if (mMainFragmentListener != null) {
                        ToastUtil.showLongToast(App.getContext().getResources().getString(R.string.refresh_device));
                        mMainFragmentListener.reScanDevice();
                    }
                }
            }
        });


        mRightImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRightClickCount++;
                if (mRightClickCount == 5) {
                    mRightClickCount = 0;

                    if (mMainFragmentListener != null) {
                        ToastUtil.showLongToast(App.getContext().getResources().getString(R.string.enter_edit));
                        mMainFragmentListener.goToEditFrag();
                    }
                }
            }
        });

        mLeftLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.i(TAG, "mLeftLayout");
                mMainPresenter.switchPage(mPositionPageIndex, false);

            }
        });

        mRightLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.i(TAG, "mRightLayout");
                mMainPresenter.switchPage(mPositionPageIndex, true);
            }
        });


        mGridView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {


                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        mPoint2DownX = event.getX();
                        LogUtil.i(TAG, "ACTION_DOWN");

                        break;
                    case MotionEvent.ACTION_MOVE:

                        break;
                    case MotionEvent.ACTION_CANCEL:
                        break;
                    case MotionEvent.ACTION_UP:
                        LogUtil.i(TAG, "ACTION_UP");

                        mPoint2MoveX = event.getX();
                        float diff = mPoint2MoveX - mPoint2DownX;
                        LogUtil.i(TAG, "ACTION_MOVE--" + "mPoint2DownY:" + mPoint2DownX
                                + "--point2MoveX:" + mPoint2MoveX + "--diff:" + diff);

                        if (diff > 5) {
                            LogUtil.i(TAG, "diff > 10");
                            mMainPresenter.switchPage(mPositionPageIndex, false);
                        } else if (diff < -5) {
                            LogUtil.i(TAG, "diff < -10");
                            mMainPresenter.switchPage(mPositionPageIndex, true);
                        }

                        break;
                    default:
                        break;
                }

                return true;
            }
        });


    }


    @Override
    protected void initData() {
        showErrorLayout(true,ERROR_LOADING);
        mMainPresenter = new MainPresenterImpl(this);
    }


    @Override
    protected void onShow() {

    }

    @Override
    protected void onHide() {

    }


    public void refreshUI(ArrayList<IOTHuiJu> iotHuiJuList) {
        mIOTHuiJuList = iotHuiJuList;

        if (mMainPresenter != null){
            mMainPresenter.setData(mIOTHuiJuList);
            mMainPresenter.refreshPage(0);
        }

    }

    public void showNoLoginErrorLayou() {
        showErrorLayout(true, ERROR_NO_WIFI);
    }



    public void showErrorLayoutEvent() {
        if (mDataSize > 0) {
            showErrorLayout(false, ERROR_LOADING);
        } else {
            showErrorLayout(true, ERROR_NO_DATA);
        }
    }

    public void showErrorLayout(final boolean isError, final int errorCode) {

        UIUtils.postTaskSafely(new Runnable() {

            @Override
            public void run() {
                if (isError) {
                    if (mErrorLayout != null){
                        mErrorLayout.setVisibility(VISIBLE);

                        if (mErrorImg.getAnimation() != null) {
                            mErrorImg.clearAnimation();
                        }

                        switch (errorCode) {
                            case ERROR_LOADING:
                                mErrorImg.setImageResource(R.drawable.icon_loading);
                                mErrorTv.setText(R.string.error_loading);

                                if (mCircleAnim != null) {
                                    mErrorImg.startAnimation(mCircleAnim);
                                } else {
                                    mCircleAnim = AnimationUtils.loadAnimation(getContext(), R.anim.anim_round_rotate);
                                    LinearInterpolator interpolator = new LinearInterpolator();
                                    mCircleAnim.setInterpolator(interpolator);
                                    mErrorImg.startAnimation(mCircleAnim);
                                }
                                break;
                            case ERROR_NO_WIFI:

                                mErrorImg.setImageResource(R.drawable.icon_no_wifi);
                                mErrorTv.setText(R.string.error_no_wifi);
                                break;
                            case ERROR_NO_DATA:
                                mErrorImg.setImageResource(R.drawable.icon_no_data);
                                mErrorTv.setText(R.string.error_no_data);
                                break;
                            default:
                                mErrorImg.setImageResource(R.drawable.icon_no_data);
                                mErrorTv.setText(R.string.error_no_data);
                                break;
                        }
                    }

                } else {

                    if (mErrorLayout != null){
                        if (mErrorImg != null && mErrorImg.getAnimation() != null) {
                            mErrorImg.clearAnimation();
                        }

                        mErrorLayout.setVisibility(GONE);
                    }


                }
            }
        });

    }

}
